package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.system.dto.SysDepartmentDTO;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.SysDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
public class SysDepartmentServiceImpl implements SysDepartmentService {

    @Autowired
    SysDepartmentMapper departmentMapper;

    @Autowired
    SysCompanyUserMapper companyUserMapper;

    @Override
    public List<SysDepartmentDTO> queryDepartmentList() {

        List<SysDepartmentDTO> departmentDTOList = this.queryChildrenDepartmentList(0L);

        return departmentDTOList;
    }

    /**
     * 查询当前企业 下 所有的顶级部门的id
     * @return
     */
    @Override
    public List<Long> queryDepartmentIds() {
        LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
        //当前企业
        departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        //顶级部门
        departmentQw.eq(SysDepartment::getParentId, 0);

        //执行查询
        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);
        //如果部门列表不为null，转换为 部门id 集合
        if(CollectionUtil.isNotEmpty(departmentList)){
            List<Long> ids = departmentList.stream().map(department -> {
                return department.getId();
            }).collect(Collectors.toList());


            return ids;
        }

        return new ArrayList<>();
    }

    @Override
    public Integer queryUserCountByDepartmentId(List<Long> departmentIds) {
        if(CollectionUtil.isEmpty(departmentIds)){
            return 0;
        }

        List<Long> ids = new ArrayList<>();
        for (Long departmentId : departmentIds) {
            ids.add(departmentId);
            //查询子部门id
            this.queryChildDepartmentIdByParentId(ids, departmentId);
        }


        //统计人数
        LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
        companyUserQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        companyUserQw.in(SysCompanyUser::getDepartmentId, ids);
        companyUserQw.eq(SysCompanyUser::getEnable, 1);
        //统计人数
        Integer count = companyUserMapper.selectCount(companyUserQw);


        return count;
    }

    @Override
    public List<DepartmentOrUserSimpleDTO> querySimpleDepartment(Long departmentId, Integer includeMember) {
        //1. 先查询子部门
        LambdaQueryWrapper<SysDepartment> departmentQw =new LambdaQueryWrapper<>();
        departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        departmentQw.eq(SysDepartment::getParentId, departmentId);
        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);


        List<DepartmentOrUserSimpleDTO> departmentSimpleDTOList = new ArrayList<>();
        //转换为返回值列表
        if(CollectionUtil.isNotEmpty(departmentList)){
            departmentSimpleDTOList = departmentList.stream().map(department -> {
                DepartmentOrUserSimpleDTO departmentSimpleDTO = new DepartmentOrUserSimpleDTO();
                departmentSimpleDTO.setType(1);
                departmentSimpleDTO.setId(department.getId());
                departmentSimpleDTO.setName(department.getName());
                return departmentSimpleDTO;
            }).collect(Collectors.toList());
        }

        List<DepartmentOrUserSimpleDTO> userSimpleDtoList = new ArrayList<>();
        //2. 是否包含员工
        if(includeMember == 0){
            //根据部门id查询员工
            LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
            companyUserQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            companyUserQw.eq(SysCompanyUser::getDepartmentId, departmentId);

            List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserQw);
            if(CollectionUtil.isNotEmpty(companyUserList)){
                userSimpleDtoList = companyUserList.stream().map(sysCompanyUser -> {
                    DepartmentOrUserSimpleDTO userSimpleDTO = new DepartmentOrUserSimpleDTO();
                    userSimpleDTO.setType(2);
                    userSimpleDTO.setId(sysCompanyUser.getId());
                    userSimpleDTO.setName(sysCompanyUser.getUserName());
                    return  userSimpleDTO;
                }).collect(Collectors.toList());
            }
        }
        //组合：把部门和员工的 数据组合到一起
        List<DepartmentOrUserSimpleDTO> resultDtoList = new ArrayList<>();
        resultDtoList.addAll(departmentSimpleDTOList);
        resultDtoList.addAll(userSimpleDtoList);


        return resultDtoList;
    }

    @Override
    public List<Long> queryDepartmentIdsByUserId(Long companyUserId) {
        List<Long> departmentIds = new ArrayList<>();

        LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
        companyUserQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        companyUserQw.eq(SysCompanyUser::getId, companyUserId);

        SysCompanyUser companyUser = companyUserMapper.selectOne(companyUserQw);
        if(companyUser != null){
            //员工所在部门id
            Long departmentId = companyUser.getDepartmentId();
            departmentIds.add(departmentId);

            while (true){
                //查询上级部门id
                LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
                departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
                departmentQw.eq(SysDepartment::getId, departmentId);
                SysDepartment department = departmentMapper.selectOne(departmentQw);
                if(department != null){

                    departmentId = department.getParentId();
                    departmentIds.add(departmentId);
                }else{
                    //如果没有查询到上级，说明是顶级部门，跳出循环
                    break;
                }
            }
        }

        return departmentIds;
    }

    /**
     *  查找 子部门id集合
     * @param ids
     * @param parentId
     */
    public void queryChildDepartmentIdByParentId(List<Long> ids ,Long parentId){
        LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
        departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        departmentQw.eq(SysDepartment::getParentId, parentId);

        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);
        if(CollectionUtil.isNotEmpty(departmentList)){
            List<Long> departmentIds = departmentList.stream().map(department -> {
                return department.getId();
            }).collect(Collectors.toList());
            //把查询到子部门id集合添加到 返回值集合中
            ids.addAll(departmentIds);

            //递归查询 子部门下的子部门id集合
            for (Long id : departmentIds) {
                this.queryChildDepartmentIdByParentId(ids, id);
            }

        }
    }



    /**
     * 查询子部门的集合
     */
    public List<SysDepartmentDTO> queryChildrenDepartmentList(Long parentId){

        LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
        departmentQw.eq(SysDepartment::getCompanyId , CurrentUserHolder.get().getCompanyId());
        departmentQw.eq(SysDepartment::getParentId , parentId);
        //查询部门
        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQw);
        // 如果不为null， 说明查询到了部门列表
        if(CollectionUtil.isNotEmpty(departmentList)){
            List<SysDepartmentDTO> departmentDTOList = BeanHelper.copyWithCollection(departmentList, SysDepartmentDTO.class);
            //查询这些部门的子部门列表
            for (SysDepartmentDTO department : departmentDTOList) {
                List<SysDepartmentDTO> departmentChildDTOList = this.queryChildrenDepartmentList(department.getId());
                department.setChildren(departmentChildDTOList);
            }
            return departmentDTOList;
        }
        return new ArrayList<>();
    }
}
